<?php
/**
 * Created by PhpStorm.
 * User: flx7
 * Date: 2017/3/9
 * Time: 16:07
 */

function curls_get(array $urls){
    $mh = curl_multi_init();

    foreach ($urls as $key => $url) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_multi_add_handle($mh, $ch);
        // 资源id，用以标识请求
        $id = (int)$ch;
        // 回调函数
        $task[$id]['callback'] = function($content)use($key) {
            global $arr;
            $arr[] = $content;
            // 请求返回后创建文件，并记录时间
            //  file_put_contents($key, time());
            if($key == 'task0')
                sleep(3);
        };
    }

    do{
        // 执行
        $status = curl_multi_exec($mh, $active);

        // 避免cpu使用率过高
        if ($active && curl_multi_select($mh) === -1)
            usleep(250);

        // 等待请求返回
        while($done = curl_multi_info_read($mh)) {
            $id = (int)$done['handle'];
            // 读取返回
            $content = curl_multi_getcontent($done['handle']);
            // 执行回调函数
            $task[$id]['callback']($content);
        }

    }while ($status === CURLM_CALL_MULTI_PERFORM || $active);

    return $GLOBALS['arr'];
}

?>